package com.tina.controller;


import com.alipay.api.AlipayApiException;
import com.tina.config.AlipayConfigInfo;
import com.tina.constant.ShopCode;
import com.tina.entity.AlipayBean;
import com.tina.entity.Orders;
import com.tina.entity.PageEntity;
import com.tina.service.IFlowersService;
import com.tina.service.IOrdersService;
import com.tina.util.AliPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author Tina
 * @since 2020-10-26
 */
@Slf4j
@RestController
@RequestMapping("/orders/")
public class OrdersController {
    private Logger logger = LoggerFactory.getLogger(OrdersController.class);
    @Autowired
    private IOrdersService ordersService;

    @Resource
    private AliPayUtil aliPayUtil;

    @Autowired
    private IFlowersService flowersService;


    /**
     * 支付宝二维码支付
     *
     * @param orders
     * @return
     */
    @PostMapping("codePay")
    public Map<String, Object> codePay(@RequestBody Orders orders) throws Exception {
        log.info("orders->{}", orders);
        // 校验商品
        flowersService.checkFood(orders.getFlowersId());
        Map<String, Object> map = new HashMap();
        String s = ordersService.confirmOrder(orders);
        return map;
    }

    /**
     * 二维码生成预订单
     *
     * @param orders
     * @return
     */
    @PostMapping("orderFrom")
    public Map<String, Object> orderFrom(@RequestBody Orders orders) {
        log.info("orders->{}", orders);

        Map<String, Object> map = new HashMap();
        try {
            // 校验商品
            flowersService.checkFood(orders.getFlowersId());
            String s = ordersService.orderFrom(orders);
            map.put("code", s != null ? 200 : 500);
            if (s != null) {
                map.put("data", s);
            }
        } catch (Exception e) {
            log.info("getMessage->{}", e);
            e.printStackTrace();
        }

        return map;
    }


    /**
     * 查询全部订单数量
     *
     * @return
     */
    @GetMapping("ordersCountNum")
    public Integer ordersCountNum(Orders orders) {
        List<Orders> orderFoods = ordersService.selectOrders(orders);
        return orderFoods.size();
    }

    /**
     * 新增订单
     *
     * @param orders
     * @param httpResponse
     * @throws IOException
     * @throws AlipayApiException
     */
    @PostMapping("add")
    public void insertOrders(@RequestBody Orders orders, HttpServletResponse httpResponse) throws IOException, AlipayApiException {
        logger.info("orders->{}", orders);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        orders.setAddTime(simpleDateFormat.format(new Date()));
        orders.setOrderId(String.valueOf(System.currentTimeMillis()));
        ordersService.insertOrders(orders);
        //2. 调用支付宝
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(orders.getOrderId());
        alipayBean.setSubject(orders.getTitle());
        alipayBean.setTotal_amount(String.valueOf(orders.getSellPrice()));
        String pay = aliPayUtil.pay(alipayBean);
        logger.info("pay->{}", pay);
        httpResponse.setContentType("text/html;charset=" + AlipayConfigInfo.charset);
        httpResponse.getWriter().write(pay);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 下单
     *
     * @param orders
     * @return
     */
    @PostMapping("confirmOrder")
    public Map<String, Object> confirmOrder(@RequestBody Orders orders) throws Exception {
        log.info("orders->{}", orders);
        // 校验商品
        flowersService.checkFood(orders.getFlowersId());
        Map<String, Object> map = new HashMap();
        String s = ordersService.confirmOrder(orders);
        map.put("code", s != null ? 200 : 500);
        if (s != null) {
            map.put("data", s);

        }
        return map;
    }

    /**
     * 支付接口
     *
     * @param orders
     */
    @PostMapping("pay")
    public String pay(@RequestBody Orders orders) throws Exception {
        log.info("orders->{}", orders);
        // 校验订单
        ordersService.checkOrder(orders.getOrderId());
        String pay = ordersService.pay(orders.getOrderId());
        log.info("pay->{}", pay);
        return pay;
    }

    /**
     * 查询全部订单
     *
     * @return
     */
    @GetMapping("list")
    public PageEntity list(Orders orders) {
        List<Orders> orderFoods = ordersService.selectOrders(orders);
        // 获得列表对象金额， 使用reduce聚合函数,实现累加器
        int size = orderFoods.stream().filter(o -> o.getStatus().equals(ShopCode.SHOP_USER_PENDING_PAYMENT.getCode())).collect(toList()).size();
        return new PageEntity(Long.valueOf(orderFoods.size()), orderFoods, String.valueOf(orderFoods.stream().filter(o -> o.getStatus() == 3).map(Orders::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add)), size < 1 ? 0 : size);
    }

}
